package cn.hd01.export.impl;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import cn.hd01.export.RowProccess;
import cn.hd01.export.exporter;

@Component
public class ExcelExporter implements exporter {

	public static final SimpleDateFormat DATA_FORMATER = new SimpleDateFormat("yyyyMMddHHmmss");

	@Override
	public <T> OutputStream export(OutputStream os, RowProccess<T> proccess, String sheetName) throws Exception {
		
		//创建HSSFWorkbook对象(excel的文档对象)  
	      HSSFWorkbook wb = new HSSFWorkbook();  
		//建立新的sheet对象（excel的表单）  
	      HSSFSheet sheet=wb.createSheet(sheetName);  
	    //在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个  
	      List<T> list = proccess.find();
	      
	      String [] titleArr = proccess.getTitle();
	      HSSFRow titleRow = sheet.createRow(0); 
	      for(int i = 0; i < titleArr.length; i++){
	    	  titleRow.createCell(i).setCellValue(titleArr[i]);
	      }

	      if(!CollectionUtils.isEmpty(list)){
	    	  for(int i = 0; i < list.size(); i++){
	    		  String[] arr = proccess.reverseProcess(list.get(i));
	    		  HSSFRow row = sheet.createRow(i + 1); 
	    		  for(int j = 0; j < arr.length; j++){
	    			  row.createCell(j).setCellValue(arr[j]);
	    	      }
	    	  }
	      }
	      
	      wb.write(os);
	      wb.close();
	      return os;
	}

}
